#ifndef _THREAD_HPP__
#define _THREAD_HPP__


#include <iostream>
#include <string>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <functional>


namespace ThreadModule
{


    static int number = 1;
    enum class TSTATUS
    {
        NEW,
        RUN,
        STOP
    };

    template<class T>
    class Thread
    {
        using func_t = std::function<void(T)>;
    private:
        static void* Routine(void* args)
        {
            Thread<T>* t = static_cast<Thread<T>*>(args);
            t->_func(t->Data());
            return nullptr;
        }

        void EnableDetach()
        {
            _joinable = false;
        }
    public:
        Thread(func_t func,T data):_func(func),_data(data),_status(TSTATUS::NEW),_joinable(true)
        {
            _name = "Thread-" + std::to_string(number++);
            _pid = getpid();
        }
        bool Start()
        {
            if(_status != TSTATUS::RUN)
            {
                int n = pthread_create(&_tid,nullptr,Routine,this);
                if(n != 0)
                {
                    return false;
                }
                _status = TSTATUS::RUN;
                return true;
            }
            return false;
        }
        bool Stop()
        {
            if(_status == TSTATUS::RUN)
            {
                int n = pthread_cancel(_tid);
                if(n != 0)
                {
                    return false;
                }
                _status = TSTATUS::STOP;
                return true;
            }
            return false;
        }
        T Data()
        {
            return _data;
        }
        bool Join()
        {
            if(_joinable)
            {
                int n = pthread_join(_tid,nullptr);
                if(n != 0)
                {
                    return false;
                }
                _status = TSTATUS::STOP;
                return true;
            }
            return false;
        }
        void Detach()
        {
            EnableDetach();
            pthread_detach(_tid);
        }
        bool IsJoinable()
        {
            return _joinable;
        }
        std::string Name()
        {
            return _name;
        }
        ~Thread()
        {

        }
    private:
        std::string _name;
        pthread_t _tid;
        pid_t _pid;
        bool _joinable;//默认不分离
        func_t _func;
        TSTATUS _status;
        T _data;
    };
};



#endif

